package com.abc.jpatest.service.impl;

import java.util.concurrent.Callable;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import com.abc.jpatest.service.TransactionService;

@Service
public class TransactionServiceImpl implements TransactionService {

    @Autowired
    private PlatformTransactionManager transactionManager;

    private ThreadLocal<TransactionStatus> threadLocal = new ThreadLocal<>();

    @Override
    public void begin() {
        /*
            1.TransactionDefinition接口被用于Spring事物支持的核心PlatformTransactionManager接口，该接口实现在特定平台（如JDBC、JTA）上执行事务管理；

            2.其核心PlatformTransactionManager.getTransaction()方法将TransactionDefinition接口作为参数，并返回TransactionStatus接口；

            3.TransactionStatus接口用于控制事务执行，即设置事务结果、检查事务是否完成或是否为新事务；
         */
        TransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
        threadLocal.set(transactionManager.getTransaction(transactionDefinition));
    }

    @Override
    public void commit() {
        transactionManager.commit(threadLocal.get());
        threadLocal.remove();
    }

    @Override
    public void rollback() {
        transactionManager.rollback(threadLocal.get());
        threadLocal.remove();
    }

    @Override
    public <V> V execute(Callable<V> callable) {
        try {
            begin();
            V result = callable.call();
            commit();
            return result;
        } catch (Exception e) {
            rollback();
            throw new RuntimeException();
        }
    }
    
}
